<?php
/*
 *                        _oo0oo_
 *                       o8888888o
 *                       88" . "88
 *                       (| -_- |)
 *                       0\  =  /0
 *                     ___/`---'\___
 *                   .' \\|     |// '.
 *                  / \\|||  :  |||// \
 *                 / _||||| -:- |||||- \
 *                |   | \\\  - /// |   |
 *                | \_|  ''\---/''  |_/ |
 *                \  .-\__  '-'  ___/-. /
 *              ___'. .'  /--.--\  `. .'___
 *           ."" '<  `.___\_<|>_/___.' >' "".
 *          | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *          \  \ `_.   \_ __\ /__ _/   .-` /  /
 *      =====`-.____`.___ \_____/___.-`___.-'=====
 *                        `=---='
 * 
 * 
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * 
 *            佛祖保佑       永不宕机     永无BUG
 * 
 *        佛曰:  
 *                写字楼里写字间，写字间里程序员；  
 *                程序人员写程序，又拿程序换酒钱。  
 *                酒醒只在网上坐，酒醉还来网下眠；  
 *                酒醉酒醒日复日，网上网下年复年。  
 *                但愿老死电脑间，不愿鞠躬老板前；  
 *                奔驰宝马贵者趣，公交自行程序员。  
 *                别人笑我忒疯癫，我笑自己命太贱；  
 *                不见满街漂亮妹，哪个归得程序员？
 * 
 * @Date         : 2020-09-02 16:48:49
 * @Author       : 真友
 * @Description  : 本代码由【真友】大力敲打
 */

declare (strict_types = 1);

namespace app\mobile\controller;

use think\facade\Request;
use think\facade\Db;
use think\facade\Cache;
use Yurun\Util\HttpRequest;
use EasyWeChat\Factory;

use Endroid\QrCode\QrCode;
use Endroid\QrCode\LabelAlignment;
use Endroid\QrCode\Response\QrCodeResponse;

class Ele extends \app\mobile\controller\Auth
{

  public function poster()
  {
    $fan = input('fan');
    $vo = Db::name('user_qrcode')
              ->where('type','ele')
              ->where('uid',$this->uid)
              ->find();
    if ($fan == 1)  {
      if (!$vo['fan_poster']) {
        $this->createPoster($vo,$fan);
      }
    }elseif ($fan == 2) {
      if (!$vo['fan_h5']) {
        $this->createPoster($vo,$fan);
      }
    }else {
      if (!$vo['poster']) {
        $this->createPoster($vo,$fan);
      }
    }
    
    $vo = Db::name('user_qrcode')
              ->where('type','ele')
              ->where('uid',$this->uid)
              ->find();
    return $this->doSuccess('ok',$vo);
    
  }

  public function doShare()
  {

    $ck = Db::name('user_qrcode')
                ->where('uid',$this->uid)
                ->where('type','ele')
                ->find();
    $share = getSettingType('饿了么');
    $share['wenan'] = "外卖红包天天领取，下单更优惠。\n".$ck['click_url'];
    return $this->doSuccess('ok',$share);

  }

  public function mini()
  {
    $uid = input('uid');
    $path = input('path');
    $relation_id = $this->user['relation_id'];
    if ($uid) $union_id = $uid;


    $base = getSettingType('基础设置');
    $ck = Db::name('user_qrcode')
                ->where('uid',$this->uid)
                ->where('type','ele')
                ->find();
    if ($ck) {
      $ck['kf_wecaht_qr'] = $base['kf_wecaht_qr'];
      $ck['we_app_info']['app_id'] = 'wxece3a9a4c82f58c9';
      return $this->doSuccess('ok',$ck);
    }
    

    $bseele = getSettingType('饿了么');


    // //订单侠 接口
    // $waimai = new \app\common\Waimai();
    // $r = $waimai->ddx_get('tbk/activityinfo',[
    //   'activity_material_id'=>$bseele['activity_material_id'],
    //   'relation_id'=>'2410500576',
    //   // 'pid'=>'2410500576',
    // ]);
    // print_r($r);
    // return;


    //淘宝官方接口
    $tb = new \app\common\TaobaoApi();
    $query = array();
    $query['activity_material_id'] = $bseele['activity_material_id'];
    $query['adzone_id'] = $bseele['adzone_id'];
    if ($relation_id) {
      $query['relation_id'] = $relation_id;
    }
    $r = $tb->get('taobao.tbk.activity.info.get',$query);
    if (isset($r['error_response'])) {
      return $this->doError($r['error_response']['sub_msg']);
    }
    $rdata = $r['tbk_activity_info_get_response']['data'];
    // print_r($rdata);


    $vv =  array();
    $vv['uid'] = $this->uid;
    $vv['click_url'] = $rdata['short_click_url'];
    $vv['wx_mini_path'] = $rdata['wx_miniprogram_path'];
    $vv['wx_qrcode_url'] = $rdata['wx_qrcode_url'];
    $vv['type'] = 'ele';
    $vv['wx_mini_appid'] = 'wxece3a9a4c82f58c9';
    $vv['ctime'] = time();
    Db::name('user_qrcode')->insert($vv);
    $ck = Db::name('user_qrcode')->where('uid',$this->uid)->where('type','ele')->find();
    $ck['kf_wecaht_qr'] = $base['kf_wecaht_qr'];

    return $this->doSuccess('ok',$ck);


    
    // print_r($rdata);
    return $this->doSuccess('ok',$res);
  }

  public function createPoster($vo = array(),$fan = 0)
  {
    $root_path = root_path();
    $dir = "/upload/poster/user";
    $poster_fname = "/poster_ele_{$this->uid}_{$fan}.png";

    $config = minicfg();
    $app = Factory::miniProgram($config);
    $scene = 'inviteZ'.$this->uid;
    $path = 'views/ele/poster';
    $qr_data = '';
    if ($fan == 1) {
      $path = 'views/ele/redbag';
      $response = $app->app_code->getUnlimit($scene, [
        // 'page'  => 'views/meituan/poster',
        'page'  => $path,
        'width' => 300,
      ]);
      
      if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
        $qr_data = $response->getBodyContents();
      }

    }elseif ($fan == 2) {
      $h5_url = Request::domain().'/h5/#/views/login/index?invite='.$this->uid;
      $qrCode = new QrCode($h5_url);
      $qrCode->setSize(400);
      $qrCode->setWriterByName('png');
      $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
      $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
      $qr_data = $qrCode->writeString();
      // print_r($h5_url);
      // return;
      # code...
    }else{
      $http = new \app\common\Http();
      $qr_data = $http->get($vo['wx_qrcode_url']);
    }
    
    

    $poster_path = $root_path.'web'.$dir.$poster_fname;
    $poster_url = Request::domain().$dir.$poster_fname;

    $poster_bg = './upload/tpl_poster_ele.jpg';

    $dir = dirname($poster_path);
    if (!file_exists($dir)) {
      mkdir($dir,0777,true);
    }

    $poster_setting = [
      'bg_url' => $poster_bg,//背景图片路径
      'image'=>[
        [
          'stream' => $qr_data, //图片资源是否是字符串图像流
          'left' => 206,
          'top' => 526,
          'width' => 340,
          'height' => 340,
        ]
      ]
    ];

    if ($fan > 0 && $this->user) {
      if ($this->user['head']) {
        $head = file_get_contents($this->user['head']);
        $poster_setting['image'][] = [
          // 'url' => 'http://api.yunkeq.com/a.png',
          'stream' => $head, //图片资源是否是字符串图像流
          'left' => 20,
          'top' => 1210,
          'width' => 100,
          'height' => 100,
        ];
      }

      $poster_setting['text'][] = [
          'text' => "【".$this->user['nick']."】邀请你点外卖",
          // 'text' => "邀请你一起买",
          'left' => 140,
          'top' => 1270,
          'fontSize' => 20, //字号
          'fontColor' => '255,0,0', //字体颜色
          'angle' => 0,
      ];
    }
    \app\common\Poster::setConfig($poster_setting);

    \app\common\Poster::make($poster_path);


    $vv =  array();
    if ($fan == 1) {
      $vv['fan_poster'] = $poster_url;
    }elseif ($fan == 2) {
      $vv['fan_h5'] = $poster_url;
    }else{
      $vv['poster'] = $poster_url;
    }
    Db::name('user_qrcode')->where('id',$vo['id'])->update($vv);

    return $this->doSuccess('ok',$vo);
  }

  //获取备案二维码
  public function relation()
  {
    $waimai = new \app\common\Waimai();
    $inviter_code = $this->user['relation_code'];
    if (!$inviter_code) {
      $r = $waimai->ddx_get('tbk/invitecode_get',[
        'code_type'=>1,
        'relation_app'=>'common',
      ]);
      if ($r['code'] == 200) {
        $inviter_code = $r['data']['inviter_code'];
        Db::name('user')->where('id',$this->uid)->update([
          'inviter_code'=>$inviter_code,
        ]);
      }
    }
    $r = $waimai->ddx_get('tbk/publisher_save_exclusive',[
      'inviter_code'=>$inviter_code,
      'callback_url'=>Request::domain().'/mobile/index/relationBack',
      'note'=>$this->uid,
      'type'=>2,
    ]);
    if ($r['code'] != 200) {
      return $this->doError($r['msg']);
    }

    $authorization_url = $r['data']['authorization_url'];

    $root_path = root_path();
    $dir = '/upload/inviter/';
    $inviter_name = "qr_inviter_{$this->uid}.png";
    $inviter_path = $root_path.'web'.$dir.$inviter_name;
    $inviter_url = Request::domain().$dir.$inviter_name;
    $sdir = dirname($inviter_path);
    if (!file_exists($sdir)) {
      mkdir($sdir,0777,true);
    }

    $qrCode = new QrCode($authorization_url);
    $qrCode->setSize(400);
    $qrCode->setWriterByName('png');
    // $qrCode->setErrorCorrectionLevel(\ErrorCorrectionLevel::HIGH());
    $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
    $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
    $qrCodeData = $qrCode->writeString();
    file_put_contents($inviter_path,$qrCodeData);
    return $this->doSuccess('ok',$inviter_url);
  }


  public function crreatePoster2()
  {

    $root_path = root_path();
    $dir = '/upload/poster/';
    $qr_fname = "qr_ele_{$this->uid}.png";
    $poster_fname = "poster_ele_{$this->uid}.png";
    $poster_fname2 = "poster2_ele_{$this->uid}.png";

    $qr_path = $root_path.'web'.$dir.$qr_fname;
    $qr_url = Request::domain().$dir.$qr_fname;

    $waimai = new \app\common\Waimai();
    // $query['relation_id'] = "1213b{$this->uid}";
    $query['relation_id'] = "{$this->uid}";
    // $query['qrcode'] = 'true';
    $res = $waimai->ddx_ele($query);
    $url = $res['data']['short_click_url'];
    $wx_qrcode_url = $res['data']['wx_qrcode_url'];
      
    $wx_miniprogram_path = $res['data']['wx_miniprogram_path'];

    //二维码的生成
    if (!file_exists($qr_path)) {
      $dir = dirname($qr_path);
      if (!file_exists($dir)) {
        mkdir($dir,0777,true);
      }
      $http = new \app\common\Http();
      $qrCodeData = $http->get($wx_qrcode_url);
      print_r($qrCodeData);
      return;
      file_put_contents($qr_path,$qrCodeData);
    }

    //海报2 显示在页面 非推广页面
    $poster_path2 = $root_path.'web'.$dir.$poster_fname2;
    $poster2_url = Request::domain().$dir.$poster_fname2;

    if (!file_exists($poster_path2)) {
      $poster2_bg = './upload/tpl_qr_ele.png';
      $qr_data = file_get_contents($qr_path);

      $dir = dirname($poster_path2);
      if (!file_exists($dir)) {
        mkdir($dir,0777,true);
      }

      \app\common\Poster::setConfig([
        'bg_url' => $poster2_bg,//背景图片路径
        'image'=>[
          [
            // 'url' => $qr_url,
            'stream' => $qr_data, //图片资源是否是字符串图像流
            'left' => 180,
            'top' => 240,
            'width' => 340,
            'height' => 340,
            // 'radius' => 50,
            // 'opacity' => 100
          ]
        ]
      ]);
      \app\common\Poster::make($poster_path2);
    }

    $poster_path = $root_path.'web'.$dir.$poster_fname;
    $poster_url = Request::domain().$dir.$poster_fname;

    if (!file_exists($poster_path)) {
      $poster_bg = './upload/tpl_poster_ele.jpg';
      $qr_data = file_get_contents($qr_path);

      $dir = dirname($poster_path);
      if (!file_exists($dir)) {
        mkdir($dir,0777,true);
      }

      \app\common\Poster::setConfig([
        'bg_url' => $poster_bg,//背景图片路径
        'image'=>[
          [
            // 'url' => $qr_url,
            'stream' => $qr_data, //图片资源是否是字符串图像流
            'left' => 206,
            'top' => 540,
            'width' => 340,
            'height' => 340,
            // 'radius' => 50,
            // 'opacity' => 100
          ]
        ]
      ]);
      \app\common\Poster::make($poster_path);
    }
    $vo =  array();
    $vo['qr_poster'] = $poster2_url;
    $vo['poster_url'] = $poster_url;
    $vo['wenan'] = '推广赚钱';
    $vo['url'] = $url;
    
    return $this->doSuccess('ok',$vo);
  }
}